// 模拟数据服务
class MockDataService {
    constructor() {
        this.videos = this.loadFromStorage('mock_videos') || this.generateVideos();
        this.comments = this.loadFromStorage('mock_comments') || this.generateComments();
        this.users = this.loadFromStorage('mock_users') || this.generateUsers();
        
        // 检查是否已经存在系统上传的视频记录
        this.checkAndMergeUploadedVideos();
        
        // 保存到本地存储
        this.saveToStorage('mock_videos', this.videos);
        this.saveToStorage('mock_comments', this.comments);
        this.saveToStorage('mock_users', this.users);
        
        console.log('模拟数据服务初始化完成');
    }
    
    // 检查并合并已上传的视频
    checkAndMergeUploadedVideos() {
        // 检查是否存在上传的视频记录
        const uploadedVideos = this.loadFromStorage('uploaded_videos');
        if (uploadedVideos && uploadedVideos.length > 0) {
            console.log('发现已上传视频:', uploadedVideos);
            
            // 合并视频数据，避免重复
            uploadedVideos.forEach(uploadedVideo => {
                const existingIndex = this.videos.findIndex(v => v.id === uploadedVideo.id);
                if (existingIndex !== -1) {
                    // 更新已存在的视频
                    this.videos[existingIndex] = uploadedVideo;
                } else {
                    // 添加新视频
                    this.videos.push(uploadedVideo);
                }
            });
        }
    }
    
    // 加载存储的数据
    loadFromStorage(key) {
        const data = localStorage.getItem(key);
        return data ? JSON.parse(data) : null;
    }
    
    // 保存数据到存储
    saveToStorage(key, data) {
        localStorage.setItem(key, JSON.stringify(data));
    }
    
    // 生成模拟用户
    generateUsers() {
        return [
            {
                id: 1,
                nickname: '测试用户',
                email: 'test@example.com',
                avatar: '/images/default-avatar.svg',
                phone: '13800138000',
                createTime: '2023-01-15T08:30:00Z'
            }
        ];
    }
    
    // 生成模拟视频
    generateVideos() {
        const titles = [
            '震撼航拍：壮美中国风光',
            '厨艺教学：家常红烧肉',
            '轻松学编程：JavaScript基础',
            '旅行Vlog：探秘云南古镇',
            '健身指南：30分钟居家训练',
            '美妆教程：日常通勤妆容',
            '科技评测：最新手机体验',
            '音乐现场：民谣吉他弹唱',
            '宠物日常：猫咪的一天'
        ];
        
        const descriptions = [
            '航拍中国各地美景，感受大好河山',
            '详细讲解家常红烧肉的制作方法和技巧',
            '从零开始学习JavaScript编程基础知识',
            '带你走进云南古镇，领略不一样的风土人情',
            '无需器械的居家健身训练，适合所有人',
            '适合日常通勤的简约妆容教程',
            '详细评测最新发布的智能手机性能和体验',
            '现场录制的民谣吉他弹唱表演',
            '记录可爱猫咪的日常生活和有趣瞬间'
        ];
        
        return Array.from({ length: titles.length }, (_, i) => ({
            id: i + 1,
            userId: 1,
            title: titles[i],
            description: descriptions[i],
            url: `/videos/video${i + 1}.mp4`,
            thumbnail: `/images/default-thumbnail.svg`,
            duration: Math.floor(Math.random() * 600) + 60, // 1-10分钟
            views: Math.floor(Math.random() * 10000),
            likes: Math.floor(Math.random() * 1000),
            createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString()
        }));
    }
    
    // 生成模拟评论
    generateComments() {
        const contents = [
            '视频拍得真好，学到了很多！',
            '感谢分享，非常实用的内容。',
            '期待更多类似的视频更新！',
            '这个技巧我试了，效果很棒！',
            '画面很美，音乐也很配！',
            '讲解得很清晰，容易理解。',
            '这个视频对我帮助很大。',
            '不错的内容，已经收藏了。',
            '建议可以再详细一点，总体很好！',
            '支持创作者，继续加油！',
            '很喜欢这种风格的视频。',
            '拍摄角度很独特，很有创意。'
        ];
        
        const comments = [];
        
        // 为每个视频生成2-5条评论
        for (let videoId = 1; videoId <= 9; videoId++) {
            const commentCount = Math.floor(Math.random() * 4) + 2; // 2-5条评论
            
            for (let j = 0; j < commentCount; j++) {
                const randomContentIndex = Math.floor(Math.random() * contents.length);
                const randomUserId = 1; // 目前只有测试用户
                const daysAgo = Math.floor(Math.random() * 14); // 0-14天前
                
                comments.push({
                    id: comments.length + 1,
                    userId: randomUserId,
                    videoId: videoId,
                    videoTitle: this.videos ? this.videos[videoId - 1]?.title || `视频${videoId}` : `视频${videoId}`,
                    content: contents[randomContentIndex],
                    createTime: new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000).toISOString(),
                    likes: Math.floor(Math.random() * 50)
                });
            }
        }
        
        return comments;
    }
    
    // 获取当前用户的信息
    getCurrentUser() {
        const storedUser = localStorage.getItem('user');
        if (storedUser) {
            try {
                const user = JSON.parse(storedUser);
                // 如果是已登录用户但没有id，添加默认id
                if (user && !user.id) {
                    user.id = 1;
                }
                return user;
            } catch (e) {
                console.error('解析用户信息失败:', e);
            }
        }
        
        // 如果没有登录或解析失败，返回默认测试用户
        return this.users[0];
    }
    
    // 获取用户信息
    getUserById(userId) {
        return this.users.find(user => user.id === userId) || null;
    }
    
    // 获取用户上传的视频
    getUserVideos(userId) {
        // 先获取当前用户
        const currentUser = this.getCurrentUser();
        console.log('获取视频用户ID:', userId, '当前用户:', currentUser);
        
        // 获取所有视频来源
        const mockVideos = this.loadFromStorage('mock_videos') || [];
        const uploadedVideos = this.loadFromStorage('uploaded_videos') || [];
        
        // 合并所有视频并去重
        const allVideos = [...mockVideos];
        uploadedVideos.forEach(video => {
            if (!allVideos.some(v => v.id === video.id)) {
                allVideos.push(video);
            }
        });
        
        // 如果用户是当前用户昵称，使用昵称匹配
        if (currentUser && currentUser.nickname) {
            const userVideos = allVideos.filter(video => {
                return video.userId === userId || 
                    (video.author && video.author === currentUser.nickname);
            });
            console.log('根据昵称匹配的视频:', userVideos);
            return userVideos;
        }
        
        return allVideos.filter(video => video.userId === userId);
    }
    
    // 获取用户的评论
    getUserComments(userId) {
        // 如果评论中有作者信息，也用作者信息匹配
        const currentUser = this.getCurrentUser();
        if (currentUser && currentUser.nickname) {
            return this.comments.filter(comment => 
                comment.userId === userId || 
                (comment.author && comment.author === currentUser.nickname));
        }
        return this.comments.filter(comment => comment.userId === userId);
    }
    
    // 添加视频
    addVideo(videoData) {
        console.log('========= mockDataService.addVideo 开始 =========');
        const newId = videoData.id || (Math.max(...this.videos.map(v => v.id), 0) + 1);
        console.log('视频ID:', newId);
        const currentUser = this.getCurrentUser();
        console.log('当前用户信息:', currentUser);
        
        const newVideo = {
            id: newId,
            userId: currentUser.id || 1,
            author: currentUser.nickname,
            ...videoData,
            views: 0,
            likes: 0,
            createTime: new Date().toISOString()
        };
        
        // 确保视频有正确的URL
        if (!newVideo.url) {
            newVideo.url = `/video/${newId}`;
            console.log('设置默认URL:', newVideo.url);
        }
        
        console.log('构建的完整视频对象:', newVideo);
        
        // 添加到视频列表
        this.videos.push(newVideo);
        
        // 保存到mock_videos
        const mockVideos = this.loadFromStorage('mock_videos') || [];
        mockVideos.push(newVideo);
        this.saveToStorage('mock_videos', mockVideos);
        console.log('已保存到mock_videos, 当前数量:', mockVideos.length);
        
        // 同时保存到上传视频记录
        const uploadedVideos = this.loadFromStorage('uploaded_videos') || [];
        uploadedVideos.push(newVideo);
        this.saveToStorage('uploaded_videos', uploadedVideos);
        console.log('已保存到uploaded_videos, 当前数量:', uploadedVideos.length);
        
        // 在实际项目中，这里应该向后端发送请求更新videos.json
        console.log('视频已添加. 在实际项目中，应该更新 /data/videos.json');
        
        console.log('========= mockDataService.addVideo 完成 =========');
        return newVideo;
    }
    
    // 更新视频
    updateVideo(videoId, videoData) {
        const index = this.videos.findIndex(v => v.id === videoId);
        if (index !== -1) {
            this.videos[index] = { ...this.videos[index], ...videoData };
            this.saveToStorage('mock_videos', this.videos);
            
            // 同时更新上传的视频记录
            const uploadedVideos = this.loadFromStorage('uploaded_videos') || [];
            const uploadedIndex = uploadedVideos.findIndex(v => v.id === videoId);
            if (uploadedIndex !== -1) {
                uploadedVideos[uploadedIndex] = { ...uploadedVideos[uploadedIndex], ...videoData };
                this.saveToStorage('uploaded_videos', uploadedVideos);
            }
            
            return this.videos[index];
        }
        return null;
    }
    
    // 删除视频
    deleteVideo(videoId) {
        const index = this.videos.findIndex(v => v.id === videoId);
        if (index !== -1) {
            this.videos.splice(index, 1);
            
            // 同时删除该视频的所有评论
            this.comments = this.comments.filter(c => c.videoId !== videoId);
            
            this.saveToStorage('mock_videos', this.videos);
            this.saveToStorage('mock_comments', this.comments);
            
            // 从上传视频记录中删除
            const uploadedVideos = this.loadFromStorage('uploaded_videos') || [];
            const filteredUploaded = uploadedVideos.filter(v => v.id !== videoId);
            this.saveToStorage('uploaded_videos', filteredUploaded);
            
            console.log('删除视频成功:', videoId);
            return true;
        }
        return false;
    }
    
    // 添加评论
    addComment(commentData) {
        const newId = Math.max(...this.comments.map(c => c.id), 0) + 1;
        const currentUser = this.getCurrentUser();
        
        const newComment = {
            id: newId,
            userId: currentUser.id || 1,
            author: currentUser.nickname,
            ...commentData,
            likes: 0,
            createTime: new Date().toISOString()
        };
        
        this.comments.push(newComment);
        this.saveToStorage('mock_comments', this.comments);
        return newComment;
    }
    
    // 删除评论
    deleteComment(commentId) {
        const index = this.comments.findIndex(c => c.id === commentId);
        if (index !== -1) {
            this.comments.splice(index, 1);
            this.saveToStorage('mock_comments', this.comments);
            return true;
        }
        return false;
    }
    
    // 更新用户信息
    updateUserProfile(userId, profileData) {
        const index = this.users.findIndex(u => u.id === userId);
        if (index !== -1) {
            this.users[index] = { ...this.users[index], ...profileData };
            this.saveToStorage('mock_users', this.users);
            
            // 如果是当前登录用户，同时更新localStorage中的user
            const currentUser = JSON.parse(localStorage.getItem('user') || '{}');
            if (currentUser.id === userId || !currentUser.id) {
                const updatedUser = { ...currentUser, ...profileData };
                if (!updatedUser.id) updatedUser.id = userId;
                localStorage.setItem('user', JSON.stringify(updatedUser));
            }
            
            return this.users[index];
        }
        return null;
    }

    // 上传视频
    async uploadVideo(formData) {
        console.log('========= mockDataService.uploadVideo 开始 =========');
        try {
            const currentUser = this.getCurrentUser();
            console.log('当前用户信息:', currentUser);
            if (!currentUser) {
                console.error('上传失败：未找到用户信息');
                throw new Error('请先登录');
            }

            const videoFile = formData.get('video');
            const thumbnailFile = formData.get('thumbnail');
            console.log('视频文件信息:', videoFile ? {
                name: videoFile.name,
                size: videoFile.size,
                type: videoFile.type
            } : null);
            console.log('缩略图文件信息:', thumbnailFile ? {
                name: thumbnailFile.name,
                size: thumbnailFile.size,
                type: thumbnailFile.type
            } : null);

            // 生成视频数据
            const videoId = Date.now() + '-' + Math.floor(Math.random() * 100000000);
            const filename = videoId + '-' + videoFile.name;
            console.log('生成的视频ID:', videoId);
            console.log('生成的文件名:', filename);

            const videoData = {
                id: videoId,
                title: formData.get('title'),
                description: formData.get('description'),
                filename: filename,
                thumbnail: thumbnailFile ? (videoId + '-' + thumbnailFile.name) : `${videoId}.jpg`,
                author: currentUser.nickname,
                authorId: currentUser.id,
                views: 0,
                likes: 0,
                comments: 0,
                createdAt: new Date().toISOString(),
                url: `/video/${videoId}`,
                filepath: `/uploads/videos/${filename}`
            };
            console.log('生成的视频数据:', videoData);

            // 保存到本地存储（仅用于演示）
            console.log('开始调用addVideo方法...');
            const savedVideo = this.addVideo(videoData);
            console.log('addVideo方法返回结果:', savedVideo);
            
            // 实际项目中，这里应该向后端发送请求保存videos.json
            const videosJsonPath = '/data/videos.json';
            console.log(`实际项目中，应该将视频数据保存到: ${videosJsonPath}`);
            
            console.log('========= mockDataService.uploadVideo 完成 =========');
            return savedVideo;
        } catch (error) {
            console.error('上传视频失败:', error);
            throw error;
        }
    }
}

// 初始化模拟数据服务
const mockDataService = new MockDataService(); 